package com.heiyu.controller;

import com.google.common.collect.Maps;
import com.heiyu.controller.response.BaseResponse;
import com.heiyu.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Api(tags = "文件存储模块",description = "文件操作接口")
@RestController
@RequestMapping("file")
public class FileController extends ApiBaseController {


    @ApiOperation(value = "文件上传",notes = "上传文件接口")
    @ApiImplicitParam(value = "file",name = "上传的文件")
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public BaseResponse upload(@RequestParam("file") MultipartFile[] file){
        BaseResponse response  = new BaseResponse();
        StringBuilder sb = new StringBuilder();
        String fileName;
        for(MultipartFile f:file){
            fileName = FileUtils.upload(f);
            if(StringUtils.isEmpty(fileName)){
                response.error("文件文成不存在");
                return response;
            }
            sb.append(fileName).append(",");
        }
        response.success();
        response.setData(sb.substring(0,sb.length()-1));
       return response;
    }

    @ApiOperation(value = "文件上传",notes = "上传文件接口")
    @ApiImplicitParam(value = "editor/upload/put",name = "上传的文件")
    @RequestMapping(value = "editor/upload/put",method = RequestMethod.POST)
    public Map<String,Object> editorUpload(@RequestParam("file") MultipartFile[] file){
        String fileName;
            fileName = FileUtils.upload(file[0]);
            if(StringUtils.isEmpty(fileName)){
              return Maps.newHashMap();
            }

        Map<String,Object> map = Maps.newHashMap();
            map.put("name",file[0].getOriginalFilename());
            map.put("original",file[0].getOriginalFilename());
            map.put("state","SUCCESS");
            map.put("type",fileName.substring(fileName.lastIndexOf(".")));
            map.put("url",fileName);
            return map;
    }


    @ApiOperation(value = "文件上传",notes = "上传文件接口")
    @ApiImplicitParam(value = "upload",name = "上传的文件")
    @RequestMapping(value = "upload",method = RequestMethod.GET)
    public Map<String,Object> uploadGet(){
        Map<String,Object> response= Maps.newHashMap();
        response.put("imageActionName","uploadImg");
        response.put("fileManagerListPath","/file/upload/put");
        response.put("imageFieldName","file");
        response.put("imageUrlPrefix","");
        return response;
    }
}
